<template>
	<view>
		<cu-custom class="navBox" bgColor="bg-blue" :isBack="true">
			<block slot="content">地图轨迹</block>
		</cu-custom>

		<view class="container">
			<map id='map' :latitude="latitude" :longitude="longitude" :markers="covers" :style="{ width: '100%', height: mapHeight + 'px' }"
			 :scale="8" :polyline="polyline" :show-location="true">
			</map>

			<view class="selectBox">
				<view class="select-item">
					<text>起点：</text>
					<view class="picker" @tap="chooseLocation('start')">
						{{startCity || '点击选择起点位置'}}
					</view>
				</view>
				
				<!-- 途径城市 -->
				<view v-for="(waypoint, index) in waypoints" :key="index" class="select-item">
					<view class="waypoint-header">
						<text>途径{{index + 1}}：</text>
						<text class="delete-btn" @tap="deleteWaypoint(index)" v-if="waypoint.city">×</text>
					</view>
					<view class="picker" @tap="chooseLocation('waypoint', index)">
						{{waypoint.city || '点击选择途径位置'}}
					</view>
				</view>
				
				<view class="select-item">
					<text>终点：</text>
					<view class="picker" @tap="chooseLocation('end')">
						{{endCity || '点击选择终点位置'}}
					</view>
				</view>
			</view>

			<view class="btnBox">
				<button :disabled="!startLocation || !endLocation" @click="planRoute" class="cu-btn bg-blue round shadow lg" style="margin-bottom: 20rpx;">规划路线</button>
				<button :disabled="isDisabled" @click="start" class="cu-btn bg-red round shadow lg">轨迹回放</button>
			</view>
		</view>
	</view>
</template>

<script>
	import QQMapWX from "@/common/qqmap-wx-jssdk.js";
	
	
	export default {
		data() {
			return {
				map: null,
				windowHeight: 0,
				mapHeight: 0,
				timer: null,
				
				isDisabled: true,
				isStart: false,
				playIndex: 1,
				
				// 默认路线数据
				defaultRoute: {
					start: {
						city: "福州站",
						location: {
							lat: 26.113859,
							lng: 119.320117
						}
					},
					waypoints: [
						{
							city: "杭州站",
							location: {
								lat: 30.243749,
								lng: 120.182488
							}
						},
						{
							city: "上海站",
							location: {
								lat: 31.249601,
								lng: 121.455704
							}
						},
						{
							city: "北京站",
							location: {
								lat: 39.902802,
								lng: 116.427048
							}
						}
					],
					end: {
						city: "沈阳站",
						location: {
							lat: 41.794601,
							lng: 123.393368
						}
					}
				},
				
				startCity: '', // 选择的起点城市
				endCity: '',   // 选择的终点城市
				startLocation: null, // 起点坐标
				endLocation: null,   // 终点坐标
				
				id: 0,
				title: 'map',
				latitude: 35.0,  // 修改默认中心点为全国中心位置
				longitude: 120.0,
				
				// 标记点
				covers: [],
				// 线
				polyline: [],
				// 当前使用的坐标数据
				coordinate: [],
				
				qqmapsdk: null, // 腾讯地图SDK实例
				waypoints: Array(3).fill().map(() => ({
					city: '',
					location: null
				})),
				// 移动标记点
				movingMarker: null,
				animationTimer: null,
				
				// 小车角度
				carAngle: 0,
			}
		},
		onLoad() {
			// 初始化腾讯地图SDK
			this.qqmapsdk = new QQMapWX({
				key: 'H5OBZ-LS6L3-DNC3B-OV45S-ZUT45-V2BRV'
			});
			
			// 获取系统信息设置地图高度
			uni.getSystemInfo({
				success: (res) => {
					this.windowHeight = res.windowHeight;
					// 设置地图高度为屏幕高度的70%
					this.mapHeight = res.windowHeight * 0.7;
				}
			});
			
			// 加载默认路线数据
			this.loadDefaultRoute();
		},
		methods: {
			// 加载默认路线数据
			loadDefaultRoute() {
				// 设置起点
				this.startCity = this.defaultRoute.start.city;
				this.startLocation = this.defaultRoute.start.location;
				
				// 设置途径点
				this.defaultRoute.waypoints.forEach((wp, index) => {
					this.waypoints[index] = {
						city: wp.city,
						location: wp.location
					};
				});
				
				// 设置终点
				this.endCity = this.defaultRoute.end.city;
				this.endLocation = this.defaultRoute.end.location;
				
				// 更新地图显示
				this.updateMapView();
				
				// 自动规划路线
				this.$nextTick(() => {
					this.planRoute();
				});
			},
			// 选择位置
			chooseLocation(type, index) {
				uni.chooseLocation({
					success: (res) => {
						if(type === 'start') {
							this.startCity = res.name;
							this.startLocation = {
								lat: res.latitude,
								lng: res.longitude
							};
						} else if(type === 'waypoint') {
							this.waypoints[index] = {
								city: res.name,
								location: {
									lat: res.latitude,
									lng: res.longitude
								}
							};
						} else {
							this.endCity = res.name;
							this.endLocation = {
								lat: res.latitude,
								lng: res.longitude
							};
						}
						
						// 更新地图显示
						this.updateMapView();
					}
				});
			},
			
			// 删除途径点
			deleteWaypoint(index) {
				this.waypoints[index] = {
					city: '',
					location: null
				};
				this.updateMapView();
			},
			
			// 规划路线
			async planRoute() {
				if(!this.startLocation || !this.endLocation) return;
				
				uni.showLoading({
					title: '规划路线中...'
				});
				
				try {
					// 打印起点信息
					console.log('路线规划信息：');
					console.log('起点:', {
						城市: this.startCity,
						纬度: this.startLocation.lat,
						经度: this.startLocation.lng
					});
					
					// 收集所有有效的途径点
					const validWaypoints = this.waypoints.filter(wp => wp.location !== null);
					
					// 打印途径点信息
					validWaypoints.forEach((wp, index) => {
						console.log(`途径点${index + 1}:`, {
							城市: wp.city,
							纬度: wp.location.lat,
							经度: wp.location.lng
						});
					});
					
					// 打印终点信息
					console.log('终点:', {
						城市: this.endCity,
						纬度: this.endLocation.lat,
						经度: this.endLocation.lng
					});
					
					// 如果没有途径点，直接规划起点到终点的路线
					if(validWaypoints.length === 0) {
						const points = await this.planSingleRoute(this.startLocation, this.endLocation);
						this.coordinate = points;
						console.log('路线坐标点:', this.coordinate);
					} else {
						// 构建完整路线：起点 -> 途径点1 -> 途径点2 -> ... -> 终点
						const allPoints = [this.startLocation, ...validWaypoints.map(wp => wp.location), this.endLocation];
						const routeSegments = [];
						
						// 规划每一段路线
						for(let i = 0; i < allPoints.length - 1; i++) {
							const from = allPoints[i];
							const to = allPoints[i + 1];
							const segment = await this.getRouteSegment(from, to);
							routeSegments.push(segment);
							
							// 打印每段路线的起终点
							console.log(`路段${i + 1}:`, {
								起点: {
									纬度: from.lat,
									经度: from.lng
								},
								终点: {
									纬度: to.lat,
									经度: to.lng
								},
								坐标点数量: segment.length
							});
						}
						
						// 合并所有路段
						this.coordinate = this.mergeRouteSegments(routeSegments);
						console.log('完整路线坐标点:', this.coordinate);
					}
					
					// 显示完整路线
					this.polyline = [{
						points: this.coordinate,
						color: '#1aad19',
						width: 4,
						arrowLine: true
					}];
					
					// 启用轨迹回放按钮
					this.isDisabled = false;
					
					uni.hideLoading();
					uni.showToast({
						title: '路线规划成功',
						icon: 'success'
					});
					
				} catch(error) {
					console.error('路线规划失败:', error);
					uni.hideLoading();
					uni.showToast({
						title: '路线规划失败',
						icon: 'none'
					});
				}
			},
			
			// 规划单段路线
			planSingleRoute(from, to) {
				return new Promise((resolve, reject) => {
					this.qqmapsdk.direction({
						mode: 'driving',
						from: {
							latitude: from.lat,
							longitude: from.lng
						},
						to: {
							latitude: to.lat,
							longitude: to.lng
						},
						success: (res) => {
							const points = this.decodePoints(res.result.routes[0].polyline);
							resolve(points);
						},
						fail: reject
					});
				});
			},
			
			// 获取路线段
			async getRouteSegment(from, to) {
				const points = await this.planSingleRoute(from, to);
				return points;
			},
			
			// 解码坐标点
			decodePoints(polyline) {
				const points = [];
				const kr = 1000000;
				
				for (let i = 2; i < polyline.length; i++) {
					polyline[i] = Number(polyline[i - 2]) + Number(polyline[i]) / kr;
				}
				
				for (let i = 0; i < polyline.length; i += 2) {
					points.push({
						latitude: polyline[i],
						longitude: polyline[i + 1]
					});
				}
				
				return points;
			},
			
			// 合并路线段
			mergeRouteSegments(segments) {
				const mergedPoints = [];
				
				segments.forEach((segment, index) => {
					// 如果不是第一段，去掉重复的起点
					if(index > 0) {
						segment.shift();
					}
					mergedPoints.push(...segment);
				});
				
				return mergedPoints;
			},
			
			// 更新地图显示
			updateMapView() {
				// 更新所有标记点
				this.covers = [];
				
				// 添加起点标记
				if(this.startLocation) {
					this.covers.push({
						id: 1,
						width: 25,
						height: 35,
						latitude: this.startLocation.lat,
						longitude: this.startLocation.lng,
						iconPath: '/static/location.png',
						label: {
							content: '起',
							color: '#ffffff',
							bgColor: '#1aad19',
							fontSize: 14,
							borderRadius: 3,
							padding: 3,
							x: 0,
							y: 0
						},
						callout: {
							content: this.startCity,
							display: 'ALWAYS',
							fontSize: 12,
							borderRadius: 4,
							padding: 5,
							bgColor: '#ffffff'
						}
					});
				}
				
				// 添加途径点标记
				this.waypoints.forEach((waypoint, index) => {
					if(waypoint.location) {
						this.covers.push({
							id: 100 + index,
							width: 25,
							height: 35,
							latitude: waypoint.location.lat,
							longitude: waypoint.location.lng,
							iconPath: '/static/location.png',
							label: {
								content: (index + 1).toString(),
								color: '#ffffff',
								bgColor: '#1296db',
								fontSize: 14,
								borderRadius: 3,
								padding: 3,
								x: 0,
								y: 0
							},
							callout: {
								content: waypoint.city,
								display: 'ALWAYS',
								fontSize: 12,
								borderRadius: 4,
								padding: 5,
								bgColor: '#ffffff'
							}
						});
					}
				});
				
				// 添加终点标记
				if(this.endLocation) {
					this.covers.push({
						id: 2,
						width: 25,
						height: 35,
						latitude: this.endLocation.lat,
						longitude: this.endLocation.lng,
						iconPath: '/static/location.png',
						label: {
							content: '终',
							color: '#ffffff',
							bgColor: '#e64340',
							fontSize: 14,
							borderRadius: 3,
							padding: 3,
							x: 0,
							y: 0
						},
						callout: {
							content: this.endCity,
							display: 'ALWAYS',
							fontSize: 12,
							borderRadius: 4,
							padding: 5,
							bgColor: '#ffffff'
						}
					});
				}
				
				// 调整地图视野以包含所有标记点
				this.adjustViewport();
			},
			
			// 调整地图视野
			adjustViewport() {
				const points = [];
				
				if(this.startLocation) {
					points.push({
						latitude: this.startLocation.lat,
						longitude: this.startLocation.lng
					});
				}
				
				this.waypoints.forEach(waypoint => {
					if(waypoint.location) {
						points.push({
							latitude: waypoint.location.lat,
							longitude: waypoint.location.lng
						});
					}
				});
				
				if(this.endLocation) {
					points.push({
						latitude: this.endLocation.lat,
						longitude: this.endLocation.lng
					});
				}
				
				if(points.length > 0) {
					const mapContext = uni.createMapContext('map');
					mapContext.includePoints({
						points: points,
						padding: [50, 50, 50, 50]
					});
				}
			},
			
			// 开始轨迹回放
			start() {
				if(!this.coordinate.length) return;
				
				this.isDisabled = true;
				this.isStart = true;
				this.playIndex = 1;
				
				// 清除之前的定时器
				if(this.timer) {
					clearInterval(this.timer);
				}
				
				// 创建移动小车标记点
				this.movingMarker = {
					id: 3,
					width: 32,
					height: 32,
					latitude: this.startLocation.lat,
					longitude: this.startLocation.lng,
					iconPath: '/static/car.png',
					anchor: {x: 0.5, y: 0.5},
					rotate: 0
				};
				
				// 更新标记点数组
				this.covers = [
					{
						id: 1,
						width: 25,
						height: 35,
						latitude: this.startLocation.lat,
						longitude: this.startLocation.lng,
						iconPath: '/static/location.png',
						label: {
							content: '起',
							color: '#ffffff',
							bgColor: '#1aad19',
							fontSize: 14,
							borderRadius: 3,
							padding: 3,
							x: 0,
							y: 0
						},
						callout: {
							content: this.startCity,
							display: 'ALWAYS',
							fontSize: 12,
							borderRadius: 4,
							padding: 5,
							bgColor: '#ffffff'
						}
					},
					{
						id: 2,
						width: 25,
						height: 35,
						latitude: this.endLocation.lat,
						longitude: this.endLocation.lng,
						iconPath: '/static/location.png',
						label: {
							content: '终',
							color: '#ffffff',
							bgColor: '#e64340',
							fontSize: 14,
							borderRadius: 3,
							padding: 3,
							x: 0,
							y: 0
						},
						callout: {
							content: this.endCity,
							display: 'ALWAYS',
							fontSize: 12,
							borderRadius: 4,
							padding: 5,
							bgColor: '#ffffff'
						}
					},
					this.movingMarker
				];
				
				// 创建新的定时器
				this.timer = setInterval(() => {
					if(this.playIndex >= this.coordinate.length) {
						clearInterval(this.timer);
						this.isDisabled = false;
						this.isStart = false;
						return;
					}
					
					// 更新路线显示
					this.polyline = [{
						points: this.coordinate.slice(0, this.playIndex + 1),
						color: '#FF0000DD',
						width: 4,
						arrowLine: true
					}];
					
					// 获取当前点和下一个点
					const currentPoint = this.coordinate[this.playIndex - 1];
					const nextPoint = this.coordinate[this.playIndex];
					
					// 计算小车角度
					const angle = this.calculateAngle(currentPoint, nextPoint);
					
					// 更新移动标记点位置和角度
					this.movingMarker.latitude = currentPoint.latitude;
					this.movingMarker.longitude = currentPoint.longitude;
					this.movingMarker.rotate = angle;
					
					// 更新标记点数组
					this.covers = [
						{
							id: 1,
							width: 25,
							height: 35,
							latitude: this.startLocation.lat,
							longitude: this.startLocation.lng,
							iconPath: '/static/location.png',
							label: {
								content: '起',
								color: '#ffffff',
								bgColor: '#1aad19',
								fontSize: 14,
								borderRadius: 3,
								padding: 3,
								x: 0,
								y: 0
							},
							callout: {
								content: this.startCity,
								display: 'ALWAYS',
								fontSize: 12,
								borderRadius: 4,
								padding: 5,
								bgColor: '#ffffff'
							}
						},
						{
							id: 2,
							width: 25,
							height: 35,
							latitude: this.endLocation.lat,
							longitude: this.endLocation.lng,
							iconPath: '/static/location.png',
							label: {
								content: '终',
								color: '#ffffff',
								bgColor: '#e64340',
								fontSize: 14,
								borderRadius: 3,
								padding: 3,
								x: 0,
								y: 0
							},
							callout: {
								content: this.endCity,
								display: 'ALWAYS',
								fontSize: 12,
								borderRadius: 4,
								padding: 5,
								bgColor: '#ffffff'
							}
						},
						this.movingMarker
					];
					
					this.playIndex++;
				}, 100); // 每100ms移动一次
			},
			
			// 计算两点之间的角度
			calculateAngle(point1, point2) {
				const dx = point2.longitude - point1.longitude;
				const dy = point2.latitude - point1.latitude;
				let angle = Math.atan2(dy, dx) * 180 / Math.PI;
				
				// 转换为顺时针角度（地图上的角度）
				angle = 90 - angle;
				if (angle < 0) {
					angle += 360;
				}
				
				return angle;
			}
		}
	}
</script>

<style lang="scss" scoped>
.container {
	width: 100%;
	height: 100%;
	position: relative;
}

.selectBox {
	width: 90%;
	margin: 20rpx auto;
	background-color: #FFFFFF;
	border-radius: 12rpx;
	padding: 20rpx;
	box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.select-item {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	
	&:last-child {
		margin-bottom: 0;
	}
	
	text {
		width: 100rpx;
		font-size: 28rpx;
		color: #333;
	}
	
	.waypoint-header {
		display: flex;
		align-items: center;
		padding-right: 5rpx;
		
		.delete-btn {
			width: auto;
			margin-left: 10rpx;
			color: #e64340;
			font-size: 32rpx;
			padding: 0 10rpx;
		}
	}
	
	.picker {
		flex: 1;
		padding: 15rpx 20rpx;
		background-color: #F8F8F8;
		border-radius: 8rpx;
		font-size: 28rpx;
		color: #666;
	}
}

.btnBox {
	width: 90%;
	margin: 30rpx auto;
	
	.cu-btn {
		width: 100%;
		height: 80rpx;
		line-height: 80rpx;
	}
}
</style>